import React, { useState } from 'react';
import { Form, Input, Modal, Radio, Select,DatePicker,TreeSelect ,Space,Button,Steps} from 'antd';
const { Option } = Select;
const { TextArea } = Input;
const { Step } = Steps;
import { PlusOutlined,MinusCircleOutlined, ContactsOutlined } from '@ant-design/icons';
import { FormValueType, TreeNode } from '../data.d';
import styles from '../index.less';
import moment from 'moment'
const FormItem = Form.Item;
import { validatorMobile } from '@/utils/utils';
export interface CreateFormProps {

  modalVisible: boolean;
  onSubmit: (values: FormValueType,resetForm: any) => void;
  onCancel: () => void;
  devicetype:API.DeviceTypeItem[];
  protocoltype:API.DictItem[];
  driverList?:API.DriverItem;
  arealist:API.TreeNodeItem[];
  values: API.UserItem;
}

const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};

const formItemLayout = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const [formValues,setFormValues] = useState<API.DeviceItem>({ });
  const [formVals] = useState<API.DeviceItem>(props.values);
console.log(formVals)
  const validatorValue = async (_: any, value: string) => {
    const promise = Promise;
    if(Number.parseInt(value)<5){
      return promise.reject("值不能小于5");
    }
    return promise.resolve();
  };

  
  

  const [form] = Form.useForm();
  const [protocol,setProtocol]= useState<number>(1);
  const [configRow,setConfigRow]= useState<number>(6);
  
  const [currentStep, setCurrentStep] = useState<number>(0);
  const forward = () => setCurrentStep(currentStep + 1);

  const backward = () => setCurrentStep(currentStep - 1);
  const { modalVisible, onSubmit: handleAdd, onCancel,devicetype,arealist,protocoltype,driverList} = props;
  const handleNext = async () => {
    const fieldsValue = await form.validateFields();
    if (fieldsValue.onlineTime) {
      fieldsValue.onlineTime = fieldsValue.onlineTime.format('YYYY-MM-DD HH:mm:ss');
    }
    if (fieldsValue.latestMaintenanceTime) {
      fieldsValue.latestMaintenanceTime = fieldsValue.latestMaintenanceTime.format('YYYY-MM-DD HH:mm:ss');
    }
    console.log(formValues)
    console.log(fieldsValue)
    console.log(formValues)
    Object.assign(formValues, fieldsValue);
    let configs = {};
   
    if (fieldsValue.sights) {
      fieldsValue.sights.map((item) => {
        configs[item.key] =  item.value ;
      })
      formValues.protocolConfig = JSON.stringify(configs);
    }
    
    console.log(formValues);
    if (currentStep < 2) {
      forward();
    } else {
      //handleAdd(formVals);
      okHandle()
    }
  };


  const okHandle = async () => {
   
    
    handleAdd(formValues,resetForm);
 
  };


  const resetForm= async () => {
    form.resetFields();
    setCurrentStep(0);
    setFormValues({});
  };

  const getOption = (list: API.DictItem[]) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.dictCode} value={item.dictCode}>
        {item.dictValue}
      </Option>
    ))
  }
 
  const changeProtocol = (value) =>{
    setProtocol(value)
  }

  const changeDriver = (e,e1) =>{
  
    var sights=[];
    var driver= driverList[e1.key];
    if(driver.driverType==1){
      sights.push({value: driver.commandPort, key: 'commandPort'});
      sights.push({value: driver.dataBits, key: 'dataBits'});
      sights.push({value: driver.baudRate, key: 'baudRate'});
      sights.push({value: driver.stopBits, key: 'stopBits'});
      sights.push({value: driver.stopBits, key: 'parity'});
      sights.push({value: '', key: 'slaveId'});
      setConfigRow(6);
    }else{
      sights.push({value: driver.ipport, key: 'ipport'});
      setConfigRow(1);
    }
      form.setFieldsValue({sights}   );
      form.setFieldsValue({'protocolType':driver.name}   );
  }
  
  
  const renderFooter = () => {
    if (currentStep === 1) {
      return (
        <>
          <Button style={{ float: 'left' }} onClick={backward}>
            上一步
          </Button>
          <Button onClick={() => onCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            下一步
          </Button>
        </>
      );
    }
    if (currentStep === 2) {
      return (
        <>
          <Button style={{ float: 'left' }} onClick={backward}>
            上一步
          </Button>
          <Button onClick={() => onCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            完成
          </Button>
        </>
      );
    }
    return (
      <>
        <Button onClick={() => onCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleNext()}>
          下一步
        </Button>
      </>
    );
  };

  const renderContent = () => {
    if (currentStep === 0) {
      return (
        <>
           <FormItem
          label="设备名称"
          name="deviceName"
          rules={[{ required: true, message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="设备位号"
          name="deviceNo"
          rules={[{ required: true, message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
            label="所在区域"
            name="areaId"
            rules={[{ required: true, message: '请选择所在区域' }]}
          >
             <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={arealist}
            
            placeholder="请选择所在区域"
            treeDefaultExpandAll
          />
          </FormItem>
          <FormItem
            label="设备类型"
            name="deviceTypeId"
            rules={[{ required: true, message: '请选择设备类型' }]}
          >
            <Select placeholder="请选择设备类型">
            {devicetype.map((item) => (
              <Option key={item.typeId} value={item.typeId}>
                {item.typeName}
              </Option>
           ))}
            </Select>
          </FormItem>
          <FormItem
            label="设备驱动"
            name="driverId"
            rules={[{ required: true, message: '请选择设备驱动' }]}
          >
            <Select placeholder="请选择设备驱动"  onChange={(e,e1)=>changeDriver(e,e1)}>
            {driverList.map((item,index) => (
              <Option key={index} value={item.id}>
                {item.driverName} - {item.driverType==0?"网口":"串口"}
              </Option>
           ))}
            </Select>
          </FormItem>
          <FormItem
            label="通讯协议类别"
            name="protocolType"
            rules={[{ required: true, message: '请选择通讯协议类别' }]}
          >
            <Select placeholder="请选择通讯协议类别" onChange={changeProtocol}>
            {getOption(protocoltype)} 
            </Select>
          </FormItem>
         
        
            <div style={{margin:'0 0 0 158px'}}>  
          <Form.List name="sights">
            {(fields, { add, remove }) => (
              <>
                {fields.map(field => (
                  <Space key={field.key} align="baseline">
                  
                    
                    <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{width:'220px'}}
                      name={[field.name, 'key']}
                      fieldKey={[field.fieldKey, 'key']}
                      rules={[{ required: true, message: '请输入配置名' }]}
                    >
                     { field.fieldKey< configRow&& field.fieldKey<5? <Input placeholder="请输入配置名" disabled  />:  <Input placeholder="请输入配置名" />} 
                    </Form.Item>
                    {field.name ==5&& configRow==6? <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{width:'220px'}}
                      name={[field.name, 'value']}
                      fieldKey={[field.fieldKey, 'value']}
                      rules={[{ required: true, message: '请输入配置值' }]}
                    >
                        <Input   maxLength={12}  placeholder="请输入配置值"/>
                    </Form.Item>:  
                      <Form.Item
                        {...field}
                        {...formItemLayout}
                        style={{width:'220px'}}
                        name={[field.name, 'value']}
                        fieldKey={[field.fieldKey, 'value']}
                        rules={[{ required: true, message: '请输入配置值' }]}
                        
                      >
                         { field.fieldKey< configRow? <Input placeholder="请输入配置值" disabled  />:  <Input placeholder="请输入配置值" />}  
                      </Form.Item> }   
                    {field.fieldKey>=configRow?
                    <MinusCircleOutlined onClick={() => remove(field.name)} />
                    :<></>
                    }
                  
                  </Space>
                ))}
               
               
                    <Button style={{ width: '448px'}} type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加配置
                    </Button>
             
                
              </>
            )}
          </Form.List>
          </div>
        </>
      );
    }
    if (currentStep === 1) {
      return (
        <>
            <FormItem
          label="设备位置"
          name="devicePosition"
          rules={[{ required: true, message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
       
          <FormItem
          label="设备描述"
          name="deviceDesc"
          rules={[{ required: true, message: '请输入至少十个字符！', min: 10 }]}
        >
          <TextArea  placeholder="请输入" showCount maxLength={100}  />
        </FormItem>
       
        <FormItem
          label="启用状态"
          name="useState"
        >
          <Radio.Group >
            <Radio value={0} >
              不启用
            </Radio>
            <Radio value={1}>
              启用
            </Radio>
          </Radio.Group>
        </FormItem>
          <FormItem
          label="设备品牌"
          name="deviceBrand"
          rules={[{ message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="设备型号"
          name="deviceModel"
          rules={[{  message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="产品序列号"
          name="seriaNumber"
          rules={[{  message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
      
        <FormItem
            label="上线时间"
            name="onlineTime"
            rules={[]}
          >
            <DatePicker  format="YYYY-MM-DD HH:mm:ss"   showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} placeholder='请选择上线时间' style={{ width: '100%' }} />
          </FormItem>
        
        </>);
    }
    return (
      <>
       <FormItem
            label="最新维保时间"
            name="latestMaintenanceTime"
            rules={[]}
          >
            <DatePicker  format="YYYY-MM-DD HH:mm:ss"   showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} placeholder='请选择上线时间' style={{ width: '100%' }} />
          </FormItem>
          <FormItem
          label="供货商"
          name="supplier"
          >
            <Input placeholder="请输入"  />
          </FormItem>
          <FormItem
          label="供货商联系人姓名"
          name="supplierName"
          >
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem
          label="供货商联系人电话"
          name="supplierPhone"
          rules={[{ validator: validatorMobile }]}
          >
            <Input placeholder="请输入"   />
          </FormItem>
      </>
    );
  }

  return (
    <Modal
      width={800}
      destroyOnClose
      title="新增模块"
      className={styles.deviceform}
      visible={modalVisible}
      footer={renderFooter()}
      onOk={okHandle}
      onCancel={() => onCancel()}
      maskClosable={false}
    >
   
    
    
   
 

     <Steps style={{ marginBottom: 28 }} current={currentStep}>
        <Step title="基本信息1" />
        <Step title="基本信息2" />
        <Step title="基本信息3" />
      </Steps>
  
      <Form
        {...formLayout}
        form={form}
        initialValues={formVals}
      >
         {renderContent()}
      </Form>
       

    </Modal>
  );
};

export default CreateForm;
